package com.yksj.healthtalk.ui.login;


import sfs2x.client.core.SFSEvent;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.net.socket.SmartControlClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.ui.MainTabUI;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppUpdateManager;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.app.SettingManager;
import com.yksj.healthtalk.ui.doctorstation.DoctorHomeMainActivity;
import com.yksj.healthtalk.utils.SharePreUtils;

public class UserLoginUI extends BaseFragmentActivity implements OnClickListener{
	LodingFragmentDialog mDialog;
	EditText mUserNameEditText;
	EditText mPasswdEditText;
	CheckBox mPasswdBox;
	SmartControlClient mControlClient;
	HTalkApplication mApplication;
	
	@SuppressLint("HandlerLeak")
	final Handler mHandler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case 1://登录超时
				if(mControlClient.getLoginState() != 2){
					if(mDialog != null && mDialog.isShowing()){
						mDialog.dismissAllowingStateLoss();
						mDialog = null;
					}
					SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),"登录超时,请稍后重试!");
				}
				break;
			case 2://登录错误
				if(mDialog != null && mDialog.isShowing()){
					mDialog.dismissAllowingStateLoss();
					mDialog = null;
				}
				SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),msg.obj.toString());
				break;
			case 3://登录成功
				Intent intent;
				if(SharePreUtils.fatchLockState()){//是否已经设置首页
					 intent = new Intent(UserLoginUI.this,DoctorHomeMainActivity.class);
				}else{
					 intent = new Intent(UserLoginUI.this,MainTabUI.class);
				}
				
				intent.putExtra("isFromLogin",true);
				intent.putExtras(((Intent)msg.obj).getExtras());
				startActivity(intent);
				if(mDialog != null && mDialog.isShowing()){
					mDialog.dismissAllowingStateLoss();
					mDialog = null;
				}
				finish();
				SharePreUtils.updateLoginState(true);
				break;
			}
		};
	};
	
	final BroadcastReceiver mReceiver = new BroadcastReceiver(){
		public void onReceive(android.content.Context context, Intent intent) {
			int state = intent.getIntExtra("state",-1);
			//登录成功
			if(state == 2){
			//登录加载个人资料完成	
			}else if(state == 0){
				//是否显示协议
				mHandler.removeMessages(1);
//				boolean isShow = intent.getBooleanExtra("isShowProtocol",false);
				Message message = mHandler.obtainMessage();
				message.what = 3;
				Intent obj = new Intent();
				obj.putExtras(intent.getExtras());
				message.obj = obj;
				mHandler.sendMessage(message);
			//登录错误	
			}else if(intent.hasExtra("errormsg")){
				mHandler.removeMessages(1);
				Message message = mHandler.obtainMessage();
				message.what = 2;
				message.obj = intent.getStringExtra("errormsg");
				mHandler.sendMessage(message);
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		CoreService.actionStart(this);
		setContentView(R.layout.user_login_ui_layout);
		
		SettingManager.destory();
		ChatUserHelper.close();
		
		mApplication = HTalkApplication.getApplication();
		mControlClient = SmartControlClient.getControlClient();
		mControlClient.disconnect();//断开连接
		SharePreUtils.updateLoginState(false);
		
		mApplication.cancelNotify();
		
		initUI();

		new AppUpdateManager(this,false).checkeUpdate();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter();
		filter.addAction(SFSEvent.LOGIN);
		registerReceiver(mReceiver, filter);
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		mHandler.removeMessages(1);
		unregisterReceiver(mReceiver);
	}
	
	private void initUI(){
		findViewById(R.id.register_btn).setOnClickListener(this);
		findViewById(R.id.login_btn).setOnClickListener(this);
		findViewById(R.id.find_paswd).setOnClickListener(this);
		mPasswdBox = (CheckBox)findViewById(R.id.remember_pas);
		mUserNameEditText = (EditText)findViewById(R.id.user_name);
		mPasswdEditText = (EditText)findViewById(R.id.passwd);
		
		String[] cache = SharePreUtils.fatchUserLoginCache();
		mUserNameEditText.setText(cache[0]);
		if(SharePreUtils.fatchisLoginCache()){
			mPasswdEditText.setText(cache[1]);
			mPasswdEditText.setTag(cache[1]);
			mPasswdBox.setChecked(true);
		}
		
		mPasswdEditText.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				mPasswdEditText.removeTextChangedListener(this);
				mPasswdEditText.setTag(null);
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		
		mPasswdEditText.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
			if(event!=null && KeyEvent.ACTION_DOWN == event.getAction() && keyCode==KeyEvent.KEYCODE_ENTER){
				onLogin();
				return true;
			}
				return false;
			}
		});
		
		mPasswdEditText.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(actionId == EditorInfo.IME_ACTION_GO){
					onLogin();
					return true ;
				}
				return false;
			}
		});
	}
	
	@Override
	public void onBackPressed() {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.register_btn:
			Intent intent = new Intent(this,UserRegisteUI.class);
			startActivity(intent);
			break;
		case R.id.login_btn:
			onLogin();
			break;
		case R.id.find_paswd://找回密码
			intent = new Intent(this,ResetPasswordUI.class);
			startActivity(intent);
			break;
		}
	}
	
	private void onLogin(){
		if(!mApplication.isNetWork()){
			SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),"网络不可用");
			return;
		}
		
		String name = mUserNameEditText.getEditableText().toString();
		String password = mPasswdEditText.getEditableText().toString();
		if(name.length() == 0){
			mUserNameEditText.setError("账号不能为空");
			return;
		}
		if(password.length() == 0){
			mPasswdEditText.setError("密码不能为空");
			return;
		}
		if(mPasswdEditText.getTag() != null){
			password = mPasswdEditText.getTag().toString();
		}
		mHandler.sendEmptyMessageDelayed(1,SmartControlClient.CONNECTION_TIMEOUT);
		mDialog = LodingFragmentDialog.showLodingDialog(getSupportFragmentManager(),"登录中...");
		mDialog.setCancelable(false);
		mControlClient.setUserPassword(name, password);
		mControlClient.setLoginState(0);
		SharePreUtils.saveUserLoginCache(name, mControlClient.getPassword(), mPasswdBox.isChecked());
		CoreService.actionLogin(this);
	}
	
}
